﻿// SyncServer.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include<boost/asio.hpp>
#include<memory>
#include<set>

using namespace std;

using boost::asio::ip::tcp;
const int max_length = 1024;
typedef std::shared_ptr<tcp::socket> socket_ptr;
std::set<std::shared_ptr<std::thread>> thread_set;

// 处理客户端的链接的处理，在线程中运行
void session(socket_ptr sock) {
	try
	{
		for (;;)
		{
			char data[max_length];
			memset(data, '\0', max_length);
			boost::system::error_code error;

			size_t length = sock->read_some(boost::asio::buffer(data,max_length),error);
			if (error==boost::asio::error::eof)
			{
				std::cout << "connection closed by peer" << std::endl;
				break;
			}
			else if(error)
			{
				throw boost::system::system_error(error);
			}

			std::cout << "recieve from" <<sock->remote_endpoint().address().to_string() << std::endl;
			std::cout << "recieve message is" <<data<< std::endl;

			// 数据回传给对方
			boost::asio::write(*sock, boost::asio::buffer(data, length));
		}
	}
	catch (const std::exception& e)
	{
		cout << "Exception in thread, code is " << e.what()  << endl;

	}
}


void server(boost::asio::io_context& io_context,unsigned short port) {
	// 接收客户端的链接，上下文，绑定服务器IPV4 地址
	tcp::acceptor a(io_context, tcp::endpoint(tcp::v4(), port));
	for (;;)
	{
		socket_ptr socket(new tcp::socket(io_context));
		a.accept(*socket);

		// 新建线程进行处理
		auto t = std::make_shared<std::thread>(session,socket);
		// 防止线程不被回收，for 循环时局部变量回收，放入一个set集合，线程的计数规则
		thread_set.insert(t);
	}
}

int main()
{
    std::cout << "Hello Server!\n";
	try
	{
		// 需要等待子线程都处理完成
		boost::asio::io_context ioc;
		server(ioc, 10086);
		for (auto& t : thread_set) {
			t->join();
		}
	}
	catch (const std::exception& e)
	{
		cout << "Exception in thread, code is " << e.what() << endl;
	}

}

